<?php

namespace app\common\controller\zhongzhuanv2;

use app\admin\library\Auth;
use think\Config;
use think\Controller;
use think\Db;
use baiying\lib\BYTokenClient;

/**
 * 后台控制器基类
 */
class Autotasktongbu extends Controller{
    
    
    /**
     * 
     * @param type $request_data
     * $list = [
            array(
                "followUserId" => ,
                "mobile" => 18300000015,
                "name" => "测试数据15",
                "fields"=>[
                    '82705932'=>'C级(明确拒绝)',
                    '82720068'=>'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/20240807/20240807NbT05l8528034362_19553058820.mp3'
                ]
            )
        ];
     */
    public static function startTongbu($request_data){
        
        $access_token = $request_data['access_token'];
        $companyId = $request_data['companyId'];
        
        
        $prev_requst_time = db('ec_ai_task_request')->where('version',2)->order('id desc')->value('createtime');
        if(time() - $prev_requst_time < 3 * 10){  //每10分钟 执行一次
            return ;
        }
        echo date("Y-m-d H:i:s") ."V2\r\n";
        
        $uuid = md5(uniqid());
        $id = db('ec_ai_task_request')->insertGetId([
            'method'=>'ai_task',
            'version'=>2,
            'uuid'=>$uuid,
            'createtime'=>time(),
        ]);
        
        $startDate = '2025-06-19';
        
        $currentPage = 1;
        while (true){
            $item_param = ['pageNum'=>$currentPage,'pageSize'=>20,'createDate'=>$startDate];
            $response = self::getAiTaskList($item_param,$access_token,$companyId);
            qqq('tongbu_ai_task',$response);
            if($response['code'] == 200){
                self::taskInsert($response['data']['list']);

                db('ec_ai_task_request_page')->insert([
                    'ec_ai_task_request_id'=>$id,
                    'currentpage'=>$response['data']['pageNum'],
                    'config'=> json_encode($response,JSON_UNESCAPED_UNICODE),
                ]);
                
                $currentPage = $response['data']['pageNum'] + 1;
                if($currentPage > $response['data']['pages']){
                    $msg = '成功';
                    break;
                }
            }else{
                $msg = '失败';
                break;
            }
        }
        
        db('ec_ai_task_request')->where('id',$id)->update([
            'msg'=>$msg,
            'endtime'=>time()
        ]);
        
        
    }
    
    
    
    public static function getAiTaskList($request_data,$access_token,$companyId) {
        
        $client = new BYTokenClient($access_token);

        $method = 'byai.sop.node.list/1.0.0/query'; //要调用的api名称
        $api_version = 'new'; //要调用的api版本号
        

        $my_params = ['companyId' => $companyId];
        $my_params = array_merge($my_params,$request_data);
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);
        qqq('getAiTaskList2',$result);
        
        return $result;
        
    }
    
    
    
    public static function taskInsert($data){
        if(empty($data)) return false;
        
        $fields_list = Db::getFields('fa_ec_ai_task');
        $fields = array_keys($fields_list);
        $paichu_fields = ['id','createtime','status'];
        $end_fields = array_diff($fields,$paichu_fields);
        
        $end_data = [];
        foreach ($data as $value){
            $middle_data = [];
            $value['origin'] = 1;
            $value['version'] = 2;
            foreach ($end_fields as $v){
                $middle_data[$v] = empty($value[$v]) ? '' : $value[$v];
            }
            
            $middle_data['content'] = json_encode($value,JSON_UNESCAPED_UNICODE);
            
            $is_exist = db('ec_ai_task')->field('id,callJobId,totalCount')->where('callJobId',$value['callJobId'])->find();
            if(!empty($is_exist)){
                unset($middle_data['callJobId'],$middle_data['origin'],$middle_data['status'],$middle_data['jobName']);
                if($is_exist['totalCount'] != $middle_data['totalCount']){
                    $middle_data['status'] = 1;
                }
                
                db('ec_ai_task')->where('callJobId',$value['callJobId'])->update($middle_data);
                continue;
            }else{
                $middle_data['createtime'] = time();
                $end_data[] = $middle_data;
            }
            
            
            
            
        }

        
        if(empty($end_data)) return false;
        db('ec_ai_task')->insertAll($end_data);
    }
    
    
}
